import { changeNumberToWanYi, clearUrlHttp, drawCardToBase64, DrawCardToBase64Option, handleImageUrlToWebp, replaceHtmlToSafeStr, secondsToTime, } from '../../utils'
import Card, { CardValue, LOAD_STATUS } from '../card'

export const getVideoDetail = (id: string): Promise<Record<string, VideoCardInfo>> => {
    const _data = {
        aid: 114475793451375,
        bvid: "BV1M453zvEr9",
        cid: 29864299153,
        copyright: 1,
        cover43: "http://i1.hdslb.com/bfs/archive/d3c843102e945d402e8a702c250f687ce49100a3.jpg",
        ctime: 1746762165,
        desc: "猫姐姐整理了一下往年国服周年庆的福利（比去年前瞻更全面一些）\n国服周年庆是每年最大的活动，有总共三弹的内容（三周）相当丰富！\n是真的会送好多东西呀~\n是不是越来越期待周年庆了呀！\nBGM：鹿乃 - 光の道標",
        dimension: {
            height: 1080,
            width: 1920,
            rotate: 0,
        },
        duration: 310,
        dynamic: "牢猫盘点了一下8周年可能会有的福利（基本全，比去年的前瞻更全面一些），国服周年庆是每年最大的活动，有总共三弹内容（三周）相当丰富！也会送好多东西，送最多的钻石（虽然用起来更快），一起备战周年庆吧！",
        first_frame: "http://i1.hdslb.com/bfs/storyff/n250509sa301lmuq3dn7ww39z1uw3b2v_firsti.jpg",
        mission_id: 4034301,
        owner: {
            name: "猫姐姐nya",
            mid: 41377819,
            face: "https://i1.hdslb.com/bfs/face/acc5559db9494af780b05fbf05c158995c48d023.jpg",
        },
        pic: "http://192.168.2.219:9000/smart-park/upload/20250521/d698b94bd4db9eeadfdc8300651221ff.png",
        pub_location: "上海",
        pubdate: 1746762165,
        rights: {
            arc_pay: 0,
            autoplay: 1,
            bp: 0,
            download: 0,
            elec: 0,
            hd5: 1,
            is_cooperation: 0,
            movie: 0,
            no_background: 0,
            no_reprint: 1,
            pay: 0,
            pay_free_watch: 0,
            ugc_pay: 0,
            ugc_pay_preview: 0,
        },
        short_link_v2: "https://b23.tv/BV1M453zvEr9",
        stat: {
            aid: 114475793451375,
            coin: 545,
            danmaku: 196,
            dislike: 0,
            favorite: 347,
            his_rank: 0,
            like: 3718,
            now_rank: 0,
            reply: 510,
            share: 317,
            view: 53318,
            vt: 0,
            vv: 0,
        },
        state: 0,
        tid: 172,
        title: "【碧蓝航线】国服8周年庆前瞻！送红尖尖送戒指，首充双倍重置，海量皮肤返场，邀请函祈愿池，比翼双飞新婚纱等",
        tname: "碧蓝航线",
        videos: 1,
        vt_switch: false,
    }
    return Promise.resolve({
        [id]: _data,
    })
}

export interface VideoCardInfo {
    aid: number,
    bvid: string,
    cid: number,
    cover43: string,
    ctime: number,
    desc: string,
    dimension: {
        height: number,
        width: number,
        rotate: number,
    },
    duration: number,
    dynamic: string,
    first_frame: string,
    mission_id: number,
    owner: {
        name: string,
        mid: number,
        face: string,
    },
    pic: string,
    pub_location: string,
    pubdate: number,
    rights: {
        arc_pay: number,
        autoplay: number,
        bp: number,
        download: number,
        elec: number,
        hd5: number,
        is_cooperation: number,
        movie: number,
        no_background: number,
        no_reprint: number,
        pay: number,
        pay_free_watch: number,
        ugc_pay: number,
        ugc_pay_preview: number,
    },
    short_link_v2: string,
    stat: {
        aid: number,
        coin: number,
        danmaku: number,
        dislike: number,
        favorite: number,
        his_rank: number,
        like: number,
        now_rank: number,
        reply: number,
        share: number,
        view: number,
        vt: number,
        vv: number,
    },
    state: number,
    tid: number,
    title: string,
    tname: string,
    videos: number,
    vt_switch: boolean,
    vt_display?: boolean,
}

export type VideoCardCreateValue = CardValue<VideoCardInfo>

export default class VideoCard extends Card {
    static blotName = 'video-card'
    static className = 'video-card'

    static create(value: VideoCardCreateValue) {
        const node: HTMLDivElement = super.create(value)
        if (value !== null && value?.status === LOAD_STATUS.LOADED) return node
        node.setAttribute('contenteditable', 'false')
        if (!value.src && !value.id) return node
        node.classList.add('card')
        const type = this.verify(value)
        return type === 'render' ? (this.renderHandle(value, node), node) :
            type === 'draw' ? (this.drawHandle(value, node), node) :
                node
    }
    static renderHandle(value: VideoCardCreateValue, node: HTMLElement) {
        // return node
        value.id && this.renderCard(value).then((dom: HTMLElement) => { node.appendChild(dom) })
    }
    static renderCard(value: VideoCardCreateValue) {
        const { id, info } = value
        return id && info ? createVideoCardDom(info).then((res) => {
            return res.dom
        }) : getVideoDetail(id).then((res) => {
            return createVideoCardDom(res[id]).then((res) => {
                return res.dom
            })
        })
    }
    static drawHandle(value: VideoCardCreateValue, node: HTMLElement) {
        const { id } = value
        if (id) {
            const loadingImage = this.createLoadingImage()
            node.appendChild(loadingImage)
            return this.drawCard(id, value).then((res) => {
                value.src = res
                value?.uploadHandle?.(loadingImage, value) || this.uploadHandle?.(loadingImage, value)
                return null
            })
        }
    }
    static drawCard(id: string, value: VideoCardCreateValue) {
        const render = async (v: VideoCardCreateValue['info']) => {
            const res = await createVideoCardDom(v, { draw: true, wrap: document.querySelector(this.drawWrap) as HTMLElement })
            return res.base64!
        }
        return value.info ? render(value.info) : getVideoDetail(id).then(res => {
            return render(res[id])
        })
    }
}

export const createVideoCardDom = (
    info: VideoCardCreateValue['info'],
    option?: DrawCardToBase64Option
) => {
    let t = 0
    let innerHtml = ''
    const r = option || {}
    if (info?.bvid) {
        t++
        const { title, aid, bvid, duration, stat, pic, vt_switch } = info
        const l = stat || {}
        const p = vt_switch
        const d = `holder-${t}-${bvid || aid}`
        const h = `bvid-${t}-${bvid || aid}`
        innerHtml = `
            <a id="${d}" class="row-video-holder normal-card is-pause" data-type="video" href="//www.bilibili.com/video/${bvid}?from=articleDetail" target="_blank">
                <div class="flex items-center pointer-events-none row-video-ctnr">
                    <div id="${h}" class="row-video-left" style="background-image: url(${handleImageUrlToWebp(clearUrlHttp(pic), 114 * devicePixelRatio)});">
                    <div class="pointer-events-none flex items-center justify-center row-video-mask by-pause">
                        <div class="row-video-duration">${secondsToTime(duration)}</div>
                    </div>
                    </div>
                    <div class="flex-1 min-w-0 text-left row-video-right">
                    <div class="multiple-ellipsis ${option?.draw ? 'draw' : ''} row-video-tit" data-card-type="videoAuthor" style="-webkit-box-orient: vertical;">
                        ${replaceHtmlToSafeStr(title)}
                    </div>
                    <div class="row-video-infos">
                        <div class="flex items-center video-play-infos">
                        <span>${option?.draw ? (p ? '--分钟播放' : '--播放') : p ? info.vt_display + '分钟播放' : changeNumberToWanYi(l.danmaku) + '播放'}</span>
                        <span>&nbsp;${changeNumberToWanYi(option?.draw || l.danmaku)}弹幕</span>
                        </div>
                    </div>
                    </div>
                </div>
            </a>
        `
    } else {
        innerHtml = `
            <div class="read-error-card media mobile">
                <p class="p-1"></p>
                <p class="flex items-center justify-center p-2">
                    <i class="card-icon icon-warning mr-1"></i>
                    <span>视频加载失败</span>
                </p>
                <p class="p-3"></p>
            </div>`
    }
    r.className = 'card-container video-card'
    return drawCardToBase64(innerHtml, r)
}
